import 'package:flutter_menu/biz/order/record/shop_car_controller.dart';
import 'package:flutter_menu/biz/table/select_num_dialog.dart';
import 'package:flutter_menu/exception/api_exception.dart';
import 'package:flutter_menu/menu_page.dart';
import 'package:flutter_menu/objectbox.g.dart';
import 'package:flutter_menu/route/app_route.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../data/menu_repository.dart';
import '../../model/shope_model.dart';
import '../../res/app_design.dart';

class TableController extends GetxController {
  TableModel? tableSelect;
  int? personIndex;
  final MenuRepository _api = Get.find();
  List<ShopTableInfoModel> areas = [];
  ShopTableInfoModel? areaSelect;

  @override
  void onInit() async {
    super.onInit();
    initTables();
  }

  void initTables() async {
    var tables = await _api.getTables();
    var all = ShopTableInfoModel()..areaName = "all".tr;
    all.tables = ToMany(items: tables.expand((e) => e.tables).toList());
    areas = [all, ...tables];
    areaSelect = all;

    update();
  }

  void selectArea(int areaSelect, ShopTableInfoModel info) {
    if (this.areaSelect == info) return;
    this.areaSelect = info;
    update();
  }

  void goOrder() {
    try {
      if (tableSelect == null) throw IllegalArgumentException();
      if (personIndex == null) throw IllegalArgumentException();

      int person = personIndex! + 1;
      Get.find<ShopCarController>().setTable(tableSelect, person);
      /// 栈中有购物车页面，弹栈并转回购物车
      if(AppRoutesObserver.observer.isPageInStack(MenuPages.Menu_Order_Record)){
        Get.until((route) => route.settings.name == MenuPages.Menu_Order_Record);
      }else{
        Get.offAllNamed(MenuPages.Menu_Order);
      }

    } on IllegalArgumentException catch (e) {
      print(e);
    }
  }

  void order() {
    if (tableSelect == null) {
      SmartDialog.showToast("please chose table");
      return;
    }

    Get.dialog(
        SelectNumDialog((v) {
          personIndex = v;
          Get.back();
          goOrder();
        }, select: personIndex, maxCount: tableSelect!.maxNum),
        barrierDismissible: false);
  }

  void onSelectTable(int index, TableModel table) {
    if (tableSelect != table) personIndex = null;
    tableSelect = table;
    update();
  }
}
